package com.yanqu.road.server.manger.union;

import com.yanqu.road.entity.config.parergon.DiscountShopConfig;
import com.yanqu.road.entity.config.parergon.UnionParergonConfig;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.parergon.*;
import com.yanqu.road.logic.bussiness.union.UnionParergonBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.union.Parergon;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.union.UnionParergonModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class UnionParergonMgr extends TempMgr {

    private static Map<String, UnionParergon> parergonMap;
    private static Map<Long, UnionParergonPlayer> parergonPlayerMap;

    private static Map<Integer, UnionBussinessman> bussinessmanMap;
    private static Map<Integer, List<UnionBussinessmanDetail>> bussinessmanDetailMap;

    /**
     * 当前商会--行脚商人对应数据
     */
    private static Map<String, Integer> unionBussinessmanMap;

    private static AtomicInteger maxBussinessId;

    @Override
    public boolean reloadData() {
        parergonMap = UnionParergonBussiness.getUnionParergonMap();
        parergonPlayerMap = UnionParergonBussiness.getUnionParergonPlayerMap();
        bussinessmanMap = UnionParergonBussiness.getUnionBussinessmanMap();
        bussinessmanDetailMap = UnionParergonBussiness.getUnionBussinessmanDetail();

        unionBussinessmanMap = new HashMap<>();
        bussinessmanMap.forEach((k,v)->{
            unionBussinessmanMap.put(v.getUnionId(), k);
        });

        int maxId = UnionParergonBussiness.getMaxBussinessId();
        maxBussinessId = new AtomicInteger(maxId);

        resetDay();
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (UnionParergon parergon : parergonMap.values()) {
            if (parergon.isInsertOption()) {
                UnionParergonBussiness.addUnionParergon(parergon);
            } else if (parergon.isUpdateOption()) {
                UnionParergonBussiness.updateUnionParergon(parergon);
            }
        }
        for (UnionParergonPlayer player : parergonPlayerMap.values()) {
            if (player.isInsertOption()) {
                UnionParergonBussiness.addUnionParergonPlayer(player);
            } else if (player.isUpdateOption()) {
                UnionParergonBussiness.updateUnionParergonPlayer(player);
            }
        }
        for (UnionBussinessman bussinessman : bussinessmanMap.values()) {
            if (bussinessman.isInsertOption()) {
                UnionParergonBussiness.addUnionBussinessman(bussinessman);
            } else if (bussinessman.isUpdateOption()) {
                UnionParergonBussiness.updateUnionBussinessman(bussinessman);
            }
        }
        for (List<UnionBussinessmanDetail> details : bussinessmanDetailMap.values()) {
            for (UnionBussinessmanDetail detail : details) {
                if (detail.isInsertOption()) {
                    UnionParergonBussiness.addUnionBussinessmanDetail(detail);
                } else if (detail.isUpdateOption()) {
                    UnionParergonBussiness.updateUnionBussinessmanDetail(detail);
                }
            }
        }
        return true;
    }

    /**
     * 获取联盟的副业
     * @param unionUid
     * @return
     */
    public static UnionParergon getParergon(String unionUid) {
        UnionParergon parergon = parergonMap.get(unionUid);
        if (parergon == null) {
            parergon = new UnionParergon();
            parergon.setInsertOption();
            parergon.setUnionId(unionUid);
            parergonMap.put(unionUid, parergon);
            randomParergon(parergon, true);
        }
        return parergon;
    }
    /**
     * 获取玩家经营数据
     * @param userId
     * @return
     */
    public static UnionParergonPlayer getParergonPlayer(long userId) {
        UnionParergonPlayer parergonPlayer = parergonPlayerMap.get(userId);
        if (parergonPlayer == null) {
            parergonPlayer = new UnionParergonPlayer();
            parergonPlayer.setInsertOption();
            parergonPlayer.setUserId(userId);
            parergonPlayer.setOperateTimes(GameConfig.PARERGON_OPERATE_MAX_TIMES);
            long now = System.currentTimeMillis() / 1000;
            parergonPlayer.setLastRestoreTime(now);
            parergonPlayer.setDayUnionUId("");
            parergonPlayerMap.put(userId, parergonPlayer);
        }
        return parergonPlayer;
    }

    /**
     * 经营
     * @param unionUid
     * @param parergonId
     * @return
     */
    public static UnionParergonOperateResult operate(String unionUid, int parergonId, GamePlayer player) {
        UnionParergonOperateResult result = new UnionParergonOperateResult();
        UnionParergonConfig parergonConfig = UnionConfigMgr.getParergonConfig(parergonId);
        if (parergonConfig == null) {
            result.setRet(GameErrorCode.E_PARERGON_NET_FIND);
            return result;
        }

        UnionParergon parergon = parergonMap.get(unionUid);

        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);

        int maxUnionMember = UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience());
        boolean finish = false;
        boolean hasBussinessMan = false;
        synchronized (parergon) {
            if (parergon.getParergonId() != parergonId) {
                result.setRet(GameErrorCode.E_PARERGON_HAS_FINISH);
                return result;
            }
            if (!parergon.checkPlayerId(player.getUserId(), maxUnionMember)) {
                result.setRet(GameErrorCode.E_PARERGON_OPERATE_TODAY_FULL);
                return result;
            }
            //进度增加
            int progress = parergon.getProgress();
            progress += parergonConfig.getManagePerProgress();
            parergon.setProgress(progress);
            //完成
            if (progress >= parergonConfig.getProgress()) {
                finish = true;
                //重新随机副业
                randomParergon(parergon, false);
            }
        }

        if (finish) {
            hasBussinessMan = finishParergon(player.getUserId(), parergonConfig, parergon, 1);
            result.setFindBusinessman(hasBussinessMan);
        }
        result.setFinish(finish);
        result.setParergonId(parergonId);
        //经营奖励
        BigDecimal earnSpeed = new BigDecimal(unionInfo.getTotalEarnSpeed());
        BigDecimal addSilver = earnSpeed.multiply(BigDecimal.valueOf((double)parergonConfig.getManagePar() / 1000));

        earnSpeed = new BigDecimal(player.getUserInfo().getEarnSpeed());
        BigDecimal maxSilver = earnSpeed.multiply(BigDecimal.valueOf(GameConfig.PARERGON_OPERATE_ADD_SILVER_PARAM));  //增加的银两上限
        if(addSilver.compareTo(maxSilver) > 0){
            addSilver = maxSilver;
        }
        result.setAddSilver(addSilver.setScale(0, BigDecimal.ROUND_UP).toBigInteger());
        //向所有成员同步
        syncParergonData(unionUid, result.isFinish());

        //记录日志
        LogMgr.addLogUnionParergon(player.getUserId(), unionUid, parergonId, parergon.getProgress(), finish, hasBussinessMan);
        return result;
    }

    /**
     * 经营完成
     * @param parergonConfig
     * @param parergon
     * @return 出现行脚商人时返回true
     */
    private static boolean finishParergon(long userId, UnionParergonConfig parergonConfig, UnionParergon parergon, int times) {
        //经营次数加一
        parergon.setParergonTimes(parergon.getParergonTimes() + times);
        //增加联盟日志
        UnionNoticeMgr.addNotice(null, parergon.getUnionId(), eUnionNoticeType.Parergon.getValue(), parergonConfig.getId());
        //发放完成奖励
        sendParergonReward(parergon.getUnionId(), parergonConfig);
        //判断是否出现行脚商人
        boolean hasBussinessMan = hasBussinessMan(parergonConfig, parergon);
        if (hasBussinessMan) {
            //向所有成员同步
            syncBussinessmanData(parergon.getUnionId());
        }
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        //出现商人时向商会发布信息
        if (hasBussinessMan) {
            WorldMessageProto.WorldMessageTempMsg.Builder bussinessMsg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(),
                    eMessageType.UnionBussiness.getValue(), eChatContentType.Common.getContentType(),null, System.currentTimeMillis(), 0, null);
            WorldMessageMgr.addWorldMessage(player, bussinessMsg);
        }
        return hasBussinessMan;
    }


    /**
     * 一键经营
     * @param unionUid
     * @param parergonId
     * @return
     */
    public static UnionParergonOperateResult oneKeyOperate(UnionParergonPlayer parergonPlayer, String unionUid, int parergonId, GamePlayer player, int operateTimes) {
        //当前副业的配置信息
        UnionParergonConfig parergonConfig = UnionConfigMgr.getParergonConfig(parergonId);
        //返回结果
        UnionParergonOperateResult result = new UnionParergonOperateResult();

        if (null == parergonConfig) {
            result.setRet(GameErrorCode.E_PARERGON_NET_FIND);
            return result;
        }

        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionUid);
        //商会当前副业
        UnionParergon parergon = parergonMap.get(unionUid);

        if(parergon == null){
            result.setRet(GameErrorCode.E_PARERGON_NET_FIND);
            return result;
        }

        boolean finish = false;
        boolean hasBussinessMan = false;

        synchronized (parergon) {
            int maxUnionMember = UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience());

            if (parergon.getParergonId() != parergonId) {
                result.setRet(GameErrorCode.E_PARERGON_HAS_FINISH);
                return result;
            }
            if (!parergon.checkPlayerId(player.getUserId(), maxUnionMember)) {
                result.setRet(GameErrorCode.E_PARERGON_OPERATE_TODAY_FULL);
                return result;
            }

            int availableTimes = parergonPlayer.getOperateTimes();    //可经营次数

            if(operateTimes < availableTimes){
                availableTimes = operateTimes;
            }

            //完成当前副业需要次数
            int toFinishNeedTimes = (parergonConfig.getProgress() - parergon.getProgress()) / parergonConfig.getManagePerProgress();
            if((parergonConfig.getProgress() - parergon.getProgress()) % parergonConfig.getManagePerProgress() > 0){
                toFinishNeedTimes = toFinishNeedTimes + 1;
            }


            //设置一键经营的次数
            if(toFinishNeedTimes > availableTimes){ //  未完成
                result.setOperateTimes(availableTimes);
                //进度增加
                int progress = parergon.getProgress();
                progress += availableTimes * parergonConfig.getManagePerProgress();
                parergon.setProgress(progress);
            }else{
                result.setOperateTimes(toFinishNeedTimes);
                finish = true;
                randomParergon(parergon, false);
            }
        }

        if (finish) {
            hasBussinessMan = finishParergon(player.getUserId(), parergonConfig, parergon, result.getOperateTimes());
            result.setFindBusinessman(hasBussinessMan);
        }
        result.setFinish(finish);
        result.setParergonId(parergon.getParergonId());

        //经营奖励
        BigDecimal earnSpeed = new BigDecimal(unionInfo.getTotalEarnSpeed());
        BigDecimal addSilver = earnSpeed.multiply(BigDecimal.valueOf((double)parergonConfig.getManagePar() / 1000));

        earnSpeed = new BigDecimal(player.getUserInfo().getEarnSpeed());
        BigDecimal maxSilver = earnSpeed.multiply(BigDecimal.valueOf(GameConfig.PARERGON_OPERATE_ADD_SILVER_PARAM));  //单次经营增加的银两上限
        if(addSilver.compareTo(maxSilver) > 0){
            addSilver = maxSilver;
        }

        addSilver = addSilver.multiply(BigDecimal.valueOf((double)result.getOperateTimes()));   //  累加单次奖励次数

        result.setAddSilver(addSilver.setScale(0, BigDecimal.ROUND_UP).toBigInteger());
        //向所有成员同步
        syncParergonData(unionUid, result.isFinish());

        //记录日志
        LogMgr.addLogUnionParergon(player.getUserId(), unionUid, parergonId, parergon.getProgress(), finish, hasBussinessMan);
        return result;
    }


    /**
     * 砍价
     * @param bussinessId
     * @param userId
     * @return
     */
    public static Parergon.BargainRespMsg.Builder bargain(int bussinessId, long userId) {
        Parergon.BargainRespMsg.Builder msg = Parergon.BargainRespMsg.newBuilder();
        UnionBussinessman bussinessman = bussinessmanMap.get(bussinessId);
        long now = System.currentTimeMillis() / 1000;
        int ret = checkBussinessman(bussinessman,  now);
        if (ret != 0) {
            msg.setRet(ret);
            return msg;
        }
        UnionParergonPlayer parergonPlayer = getParergonPlayer(userId);
        if (!bussinessman.getUnionId().equals(parergonPlayer.getBargainUnionUId()) ) {
            if (parergonPlayer.getBargainTime() + GameConfig.PARERGON_BARGAIN_CD_TIME > now) {
                msg.setRet(GameErrorCode.E_PARERGON_BARGAIN_TIMES_NOT_RESTORE);
                return msg;
            }
        }

        if(!bussinessmanDetailMap.containsKey(bussinessId)){
            synchronized (bussinessmanDetailMap){
                if(!bussinessmanDetailMap.containsKey(bussinessId)){
                    bussinessmanDetailMap.put(bussinessId, new ArrayList<>());
                }
            }
        }
        List<UnionBussinessmanDetail> details = bussinessmanDetailMap.get(bussinessId);
        long bargainValue;
        synchronized (bussinessman) {
            if (bussinessman.getBargainTimes() >= bussinessman.getBargainNum()) {
                msg.setRet(GameErrorCode.E_PARERGON_BARGAIN_NOT_TIMES);
                return msg;
            }
            for (UnionBussinessmanDetail detail : details) {
                if (detail.getUserId() == userId) {
                    msg.setRet(GameErrorCode.E_PARERGON_BARGAIN_HAS_DO);
                    return msg;
                }
            }

            bargainValue = bussinessman.getBargainValue(details.size());
            bussinessman.setBargainPrice(bargainValue+bussinessman.getBargainPrice());
            bussinessman.setBargainTimes(bussinessman.getBargainTimes() + 1);
            UnionBussinessmanDetail detail = new UnionBussinessmanDetail();
            detail.setInsertOption();
            detail.setBussinessId(bussinessId);
            detail.setUserId(userId);
            detail.setBargainPrice(bargainValue);
            detail.setBargainTime(now);
            detail.setHasBuy(false);
            details.add(detail);
        }

        msg.setBargainPrice(bargainValue);
        msg.setRet(0);

        //砍价成功记录玩家砍价时间
        parergonPlayer.setBargainTime(now);
        parergonPlayer.setBargainUnionUId(bussinessman.getUnionId());

        //向所有成员同步
        syncBussinessmanData(bussinessman.getUnionId());
        //向商会发一条数据
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
        WorldMessageProto.WorldMessageTempMsg.Builder chatMsg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(),
                eMessageType.UnionBargain.getValue(), eChatContentType.Common.getContentType(), String.valueOf(msg.getBargainPrice()), now * 1000, 0, null);
        WorldMessageMgr.addWorldMessage(player, chatMsg);
        return msg;
    }

    /**
     * 购买
     * @param bussinessId
     * @param player
     * @return
     */
    public static Parergon.BuyProductRespMsg.Builder buy(int bussinessId, GamePlayer player) {
        Parergon.BuyProductRespMsg.Builder msg = Parergon.BuyProductRespMsg.newBuilder();
        UnionBussinessman bussinessman = bussinessmanMap.get(bussinessId);
        long now = System.currentTimeMillis() / 1000;
        int ret = checkBussinessman(bussinessman,  now);
        if (ret != 0) {
            msg.setRet(ret);
            return msg;
        }
        List<UnionBussinessmanDetail> details = bussinessmanDetailMap.get(bussinessId);
        UnionBussinessmanDetail detail = null;
        if (details != null) {
            for (UnionBussinessmanDetail d : details) {
                if (d.getUserId() == player.getUserId()) {
                    detail = d;
                    break;
                }
            }
        }
        if (detail == null) {
            msg.setRet(GameErrorCode.E_PARERGON_BUY_NOT_BARGAIN_);
            return msg;
        }
        if (detail.isHasBuy()) {
            msg.setRet(GameErrorCode.E_PARERGON_BUY_AGAIN);
            return msg;
        }

        DiscountShopConfig shopConfig = UnionConfigMgr.getDiscountShopConfig(bussinessman.getProductId());
        long price = shopConfig.getPrice();
        price -= bussinessman.getBargainPrice();
        //扣元宝
        if (price > 0){
            Property property = new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(price));
            boolean result = player.getModule(CurrencyModule.class).removeCurrency(property,  eLogMoneyType.Union, eLogMoneyType.UnionDiscountShopBuy);
            if (!result) {
                msg.setRet(GameErrorCode.E_BAG_INGOTS_NO_ENOUGH);
                return msg;
            }
        }

        detail.setHasBuy(true);
        Property property = PropertyHelper.parseStringToProperty(shopConfig.getContent());
        if (price < 0) {
            property.addProperty(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(price * -1));
        }
        //加道具
        player.getModule(CurrencyModule.class).addCurrency(property,  eLogMoneyType.Union, eLogMoneyType.UnionDiscountShopBuy);

        msg.setReward(PropertyHelper.parsePropertyToString(property));
        msg.setRet(0);

        //向所有成员同步
        syncBussinessmanData(bussinessman.getUnionId());
        return msg;
    }

    private static int checkBussinessman(UnionBussinessman bussinessman, long now) {
        if (bussinessman == null) {
            return GameErrorCode.E_PARERGON_BARGAIN_ID_NOT_FIND;
        }

        if (bussinessman.getDisappearTime() < now) {
            return GameErrorCode.E_PARERGON_SHOP_HAS_DISAPPEAR;
        }
        return 0;
    }

    public static Parergon.OperateRecordRespMsg.Builder getOperateRecord(String unionUid) {
        Parergon.OperateRecordRespMsg.Builder msg = Parergon.OperateRecordRespMsg.newBuilder();
        Map<Long, UnionMember> unionMemberMap = UnionMgr.getUnionMemberMap(unionUid);
        long serverId = GameServer.getInstance().getServerId();
        List<Parergon.OperateRecordTempMsg.Builder> datas = new ArrayList<>();
        for (UnionMember member : unionMemberMap.values()) {
            Parergon.OperateRecordTempMsg.Builder data = Parergon.OperateRecordTempMsg.newBuilder();
            long userId = member.getUserId();
            UnionParergonPlayer parergonPlayer = getParergonPlayer(userId);
            if (parergonPlayer.getTotalTimes() <= 0) {
                continue;
            }
            UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, serverId);
            data.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            data.setTodayTimes(parergonPlayer.getTodayTimes());
            data.setTotalTimes(parergonPlayer.getTotalTimes());
            datas.add(data);
        }
        if (datas.size() > 0) {
            datas.sort((o1, o2) -> o2.getTotalTimes() - o1.getTotalTimes());
            for (Parergon.OperateRecordTempMsg.Builder data : datas) {
                msg.addRecords(data);
            }
        }
        return msg;
    }

    /**
     * 随机一个副业
     * @param parergon
     * @param first
     */
    private static void randomParergon(UnionParergon parergon, boolean first) {
        parergon.setProgress(0);
        if (first) {
            parergon.setParergonId(GameConfig.PARERGON_FIRST_ID);
        } else {
            UnionParergonConfig parergonConfig = UnionConfigMgr.getRandomUnionParergonConfig(parergon.getParergonId(), parergon.getUnionId());
            parergon.setParergonId(parergonConfig.getId());
        }
    }

    /**
     * 发放副业完成奖励
     * @param parergonConfig
     */
    public static void sendParergonReward(String unionUid, UnionParergonConfig parergonConfig) {
        Map<Long, UnionMember> unionMemberMap = UnionMgr.getUnionMemberMap(unionUid);
        if (unionMemberMap == null) {
            return;
        }
        for (UnionMember member : unionMemberMap.values()) {
            long userId = member.getUserId();
            UserInfo userInfo = UserMgr.getUserInfo(userId);
            UnionParergonPlayer parergonPlayer = getParergonPlayer(userId);
            String name = MultipleLanguageMgr.getContent(parergonConfig.getName(), userInfo.getLanguage());
            if (StringUtils.isNullOrEmpty(parergonPlayer.getDayUnionUId()) || unionUid.equals(parergonPlayer.getDayUnionUId())) {
                String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_PARERGON_FINISH_TITLE, userInfo.getLanguage());
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.UNION_PARERGON_FINISH_CONTENT, userInfo.getLanguage()), name);
                MailManager.sendMail(userId, eMailType.DAILY.getValue(), parergonConfig.getRewards(), mailContent, mailTitle);
                //记录今日获得副业奖励的商会ID
                parergonPlayer.setDayUnionUId(unionUid);
            } else {
                String mailTitle = MultipleLanguageMgr.getContent(MailManager.UNION_PARERGON_CANNOT_FINISH_TITLE, userInfo.getLanguage());
                String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.UNION_PARERGON_CANNOT_FINISH_CONTENT, userInfo.getLanguage()), name);
                MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), "", mailContent, mailTitle);
            }

        }
    }


    /**
     * 行脚商人
     * @param parergonConfig
     * @param parergon
     * @return
     */
    private static boolean hasBussinessMan(UnionParergonConfig parergonConfig, UnionParergon parergon) {
        if (unionBussinessmanMap.containsKey(parergon.getUnionId())) {
            Integer bussinessId = unionBussinessmanMap.get(parergon.getUnionId());
            UnionBussinessman bussinessman = bussinessmanMap.get(bussinessId);
            long  now = System.currentTimeMillis() / 1000;
            //行脚商人未结束就返回false
            if (bussinessman.getDisappearTime() > now) {
                return false;
            }
            //行脚商人冷却时间未到就返回false
            if (now - bussinessman.getCreateTime() < GameConfig.PARERGON_BUSSINESSMAN_CD_TIME) {
                return false;
            }
        }
        if (parergon.getParergonTimes() == 1 || UnionConfigMgr.hasShowUnionParergon(parergonConfig)) {
            UnionBussinessman bussinessMan = createBussinessMan(parergon.getUnionId(), parergon.getParergonTimes());
            bussinessmanMap.put(bussinessMan.getBussinessId(), bussinessMan);
            unionBussinessmanMap.put(parergon.getUnionId(), bussinessMan.getBussinessId());
            return true;
        }
        return false;
    }

    /**
     *初始化商人（首个商人特殊处理）
     */
    public static UnionBussinessman createBussinessMan(String unionId, int parergonTimes) {
        UnionBussinessman bussinessman = new UnionBussinessman();
        bussinessman.setBussinessId(maxBussinessId.incrementAndGet());
        bussinessman.setUnionId(unionId);
        UnionInfo unionInfo = UnionMgr.getUnionInfo(unionId);
        bussinessman.setBargainNum(UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience()));

        long now = System.currentTimeMillis() / 1000;
        long disappearTime = now + GameConfig.PARERGON_BUSSINESSMAN_DISAPPEAR_TIME;
        bussinessman.setCreateTime(now);
        bussinessman.setDisappearTime(disappearTime);
        //随机一个礼包
        DiscountShopConfig shopConfig = UnionConfigMgr.getRandomDiscountShopConfig();
        bussinessman.setProductId(shopConfig.getId());
        //砍价列表
        bussinessman.setBargainValues(UnionConfigMgr.initBargainList(bussinessman.getBargainNum(), shopConfig, parergonTimes));

        bussinessman.setInsertOption();
        return bussinessman;
    }

    /**
     * 向所有在线成员同步副业数据
     */
    private static void syncParergonData(String unionUid, boolean hasChange) {
        Parergon.ParergonMsg.Builder msg = UnionParergonMgr.parseParergonMsg(unionUid, hasChange);
        Map<Long, UnionMember> unionMemberMap = UnionMgr.getUnionMemberMap(unionUid);
        for (Long userId : unionMemberMap.keySet()) {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if (player != null) {
                player.sendPacket(Protocol.U_UNION_PARERGON_SYNC, msg);
            }
        }
    }
    /**
     * 向所有在线成员同步行脚商人数据
     */
    private static void syncBussinessmanData(String unionUid) {
        Integer bussinessId = unionBussinessmanMap.get(unionUid);
        Map<Long, UnionMember> unionMemberMap = UnionMgr.getUnionMemberMap(unionUid);

        for (Long userId : unionMemberMap.keySet()) {
            GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
            if (player != null) {
                Parergon.BusinessmanDataMsg.Builder msg = parseBusinessmanMsg(bussinessId);
                setBusinessmanStatusMsg(msg, player.getUserInfo().getNickName());
                player.sendPacket(Protocol.U_UNION_PARERGON_BUSINESSMAN, msg);
            }
        }
    }
    /**
     * 获取行脚商人id
     */
    public static Integer getBussinessman(String unionUid) {
        if (!unionBussinessmanMap.containsKey(unionUid)) {
            return null;
        }
        return unionBussinessmanMap.get(unionUid);
    }

    /**
     * 组装行脚商人数据
     * @param bussinessId
     * @return
     */
    public static Parergon.BusinessmanDataMsg.Builder parseBusinessmanMsg(int bussinessId) {
        UnionBussinessman bussinessman = bussinessmanMap.get(bussinessId);
        List<UnionBussinessmanDetail> details = bussinessmanDetailMap.get(bussinessId);
        Parergon.BusinessmanDataMsg.Builder msg = Parergon.BusinessmanDataMsg.newBuilder();
        msg.setBussinessId(bussinessId);
        msg.setBargainNum(bussinessman.getBargainNum());
        msg.setBargainTimes(bussinessman.getBargainTimes());
        msg.setProductId(bussinessman.getProductId());
        msg.setBargainPrice(bussinessman.getBargainPrice());
        msg.setDisappearTime(bussinessman.getDisappearTime());
        List<Parergon.BargainTempMsg.Builder> datas = new ArrayList<>();
        if (details != null) {
            for (UnionBussinessmanDetail detail : details) {
                Parergon.BargainTempMsg.Builder data = Parergon.BargainTempMsg.newBuilder();
                data.setNickName(UserMgr.getNickName(detail.getUserId()));
                data.setBargainPrice(detail.getBargainPrice());
                data.setHasBuy(detail.isHasBuy());
                data.setUserId(detail.getUserId());
                datas.add(data);
            }
        }
        if (datas.size() > 0) {
            datas.sort((o1, o2) -> (int) (o2.getBargainPrice() - o1.getBargainPrice()));
            for (Parergon.BargainTempMsg.Builder data : datas) {
                msg.addRecords(data);
            }
        }
        return msg;
    }

    public static void setBusinessmanStatusMsg(Parergon.BusinessmanDataMsg.Builder msg, String nickName) {
        int status = 0;
        for (Parergon.BargainTempMsg.Builder data : msg.getRecordsBuilderList()) {
            if (data.getNickName().equals(nickName)) {
                if (data.getHasBuy()) {
                    status = 2;
                } else {
                    status = 1;
                }
                break;
            }
        }
        msg.setStatus(status);
    }

    /**
     * 副业进度数据组装
     * @param unionUid
     * @param hasChange
     * @return
     */
    public static Parergon.ParergonMsg.Builder parseParergonMsg(String unionUid, boolean hasChange) {
        Parergon.ParergonMsg.Builder msg = Parergon.ParergonMsg.newBuilder();
        UnionParergon parergon = parergonMap.get(unionUid);
        msg.setParergonId(parergon.getParergonId());
        msg.setProgress(parergon.getProgress());
        msg.setHasChange(hasChange);
        return msg;
    }

    /**
     * 离开商会清理数据
     * @param unionUid
     * @param userId
     */
    public static void quitUnion(String unionUid, long userId) {
        UnionParergonPlayer parergonPlayer = getParergonPlayer(userId);
        parergonPlayer.setTodayTimes(0);
        parergonPlayer.setTotalTimes(0);
    }

    public static void resetDay() {
        long zeroTime = LocalDateTimeHelper.getZeroTimeTimeStamp() / 1000;
        long now = System.currentTimeMillis() / 1000;
        // 重置今日经营次数、商会Id
        for (UnionParergonPlayer parergonPlayer : parergonPlayerMap.values()) {
            if (parergonPlayer.getDayRestoreTime() < zeroTime) {
                parergonPlayer.setTodayTimes(0);
                parergonPlayer.setDayUnionUId("");
                parergonPlayer.setDayRestoreTime(now);
            }
        }
        // 重置副业今日可经营玩家id列表
        for (UnionParergon parergon : parergonMap.values()) {
            if (parergon.getDayRestoreTime() < zeroTime) {
                parergon.setPlayerIds("");
                parergon.setDayRestoreTime(now);
            }
        }
    }

    public static UnionParergon getUnionParergon(String unionUid){
        return parergonMap.get(unionUid);
    }

    public static Parergon.OperateRespMsg.Builder builderOperateRespMsg(UnionParergonOperateResult operateResult){
        Parergon.OperateRespMsg.Builder respMsg = Parergon.OperateRespMsg.newBuilder();
        respMsg.setRet(operateResult.getRet());
        respMsg.setOperateTimes(operateResult.getOperateTimes());
        respMsg.setLastRestoreTime(operateResult.getLastRestoreTime());
        if(0 == operateResult.getRet()){
            respMsg.setParergonId(operateResult.getParergonId());
            respMsg.setIsFinish(operateResult.isFinish());
            respMsg.setFindBusinessman(operateResult.isFindBusinessman());
            respMsg.setRewardMoney(operateResult.getAddSilver().toString());
            respMsg.setFinishTimes(operateResult.getFinishTimes());
            respMsg.setHistoryTimes(operateResult.getHistoryTimes());
        }
        return respMsg;
    }


    /**
     * 自动经营
     * @return
     */
    public static UnionParergonOperateResult autoParergonOperate(GamePlayer player){
        UnionParergonOperateResult result = new UnionParergonOperateResult();
        UnionParergonModule unionParergonModule = player.getModule(UnionParergonModule.class);
        //商会当前副业
        UnionParergon parergon = UnionParergonMgr.getUnionParergon(player.getUserInfo().getUnionUid());
        if (parergon == null) {
            result.setRet(GameErrorCode.E_PARERGON_NOT_IN_UNION);
            return result;
        }
        unionParergonModule.calOperateTimes();
        synchronized (parergon){
            result = unionParergonModule.oneKeyOperate(parergon.getParergonId(), unionParergonModule.getOperateTimes());
        }
        return result;
    }

}
